package com.appoint.buss.service.impl;

import com.appoint.buss.domain.EpiparaRnaInfo;
import com.appoint.buss.domain.EpiparaRnaSeq;
import com.appoint.buss.mapper.EpiparaRnaSeqMapper;
import com.appoint.buss.service.AsyncRnaSeqService;
import com.appoint.common.exception.ServiceException;
import com.appoint.common.utils.CreateMultipartFile;
import com.appoint.common.utils.StringUtils;
import com.appoint.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Async
@Slf4j
@Service
public class AsyncRnaSeqServiceImpl extends ServiceImpl<EpiparaRnaSeqMapper, EpiparaRnaSeq> implements AsyncRnaSeqService {

    @Value(value = "${epipara.filePath}")
    private String filePath;

    @Async
    @Override
    public void saveRnaSeq(List<EpiparaRnaInfo> paramList, String type, String operName) {
        paramList.forEach(info ->{
            String species = info.getSpecies().replace(" ","_");
            String path = species + "/" + type + "/" + info.getAccession() + "/8.differential_analysis/" + info.getIndex() + ".xlsx";
            ExcelUtil<EpiparaRnaSeq> util = new ExcelUtil<>(EpiparaRnaSeq.class);
            MultipartFile file = CreateMultipartFile.createMfileByPath(filePath + path);
            if(file == null) {
                return;
            }
            try{
                List<EpiparaRnaSeq> list = util.importExcel(file.getInputStream());
                importUser(list, path,operName,info.getIndex());
            }catch (Exception e){
                e.printStackTrace();
            }
        });
    }

    public void importUser(List<EpiparaRnaSeq> list, String path, String operName, String fileName) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        list.forEach(vo ->{
            vo.setFileName(fileName);
            vo.setFileDownPath(path);
        });
        String resultMsg = "恭喜您，数据已全部导入成功！共 " + list.size() + " 条";
        try {
            this.saveBatch(list);
        } catch (Exception e) {
            resultMsg  = "很抱歉，导入失败！";
            log.error(resultMsg, e);
        }
        log.info(resultMsg);
    }
}
